package _17_函数式编程.Lambda._9_Lambda应用;

import _17_函数式编程.Lambda.Apple;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;

public class _9_2_Lambda_Comparator {
    public static void main(String[] args) {
        List<Apple> appleList = Arrays.asList(
                new Apple("red",150),
                new Apple("green",234),
                new Apple("green",123)
        );

        List<Apple> result;

        //匿名类
        appleList.sort(new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2){
                if(o1.getWeight() > o2.getWeight()){
                    return 1;
                }
                else if(o1.getWeight() == o2.getWeight()){
                    return 0;
                }
                else{
                    return -1;
                }
            }
        });

        printByConsumer(appleList,
                (Apple apple) -> System.out.println("苹果的颜色：" + apple.getColor() + "，重量：" + apple.getWeight())
        );

        System.out.println("==========================================");

        //Lambda
        appleList.sort((Apple o1, Apple o2) ->
                {
                    if(o1.getWeight() > o2.getWeight()){
                        return 1;
                    }
                    else if(o1.getWeight() == o2.getWeight()){
                        return 0;
                    }
                    else{
                        return -1;
                    }
                }
                );

        printByConsumer(appleList,
                (Apple apple) -> System.out.println("苹果的颜色：" + apple.getColor() + "，重量：" + apple.getWeight())
                );

    }

    public static <T> void printByConsumer(List<T> list, Consumer<T> consumer){
        for (T t : list){
            consumer.accept(t);
        }
    }

}
